package com.yimiyisu.contract_cust.controller;


import com.yimiyisu.contract_cust.domain.ContractDO;
import com.yimiyisu.contract_cust.domain.MaterialDO;
import com.zen.ZenController;
import com.zen.ZenData;
import com.zen.ZenEngine;
import com.zen.ZenResult;
import com.zen.annotation.AccessRole;
import com.zen.annotation.Inject;
import com.zen.enums.ZenRole;
import com.zen.kit.JsonKit;

import java.util.List;
import java.util.Map;

@AccessRole(ZenRole.ADMIN)
public class Form extends ZenController {

    @Inject
    private ZenEngine zenEngine;

    /**
     * 查询表单的数据
     */
    public ZenResult create(ZenData data) {
        // 1.查询合同中的元素
        ContractDO contractDO = zenEngine
                .execute("get/contract", ZenData.create("id", data.get("id")))
                .asEntity(ContractDO.class);
        List<Map<String, Object>> contractField = contractDO.getField();
        if (contractField == null || contractField.isEmpty()) return ZenResult.fail("该合同没有表单元素");
        return ZenResult.success().setData(contractField);
    }

    /**
     * 获取用户输入的表单数据并修改合同元素值
     * @param data
     * @return
     */
    public ZenResult insertData(ZenData data) {
        Map fieldMap = data.parse(Map.class);
        if (data.isEmpty()) {
            return ZenResult.success();
        }
        ContractDO contractDO = zenEngine.execute("get/contract", data)
                .asEntity(ContractDO.class);
        List<Map<String, Object>> contractField = contractDO.getField();

        for (Map<String, Object> field : contractField) {
//            Object object = fieldMap.get(field.get("id"));
//            if (object.getClass().getSimpleName().equals("ArrayList")) {
//                List<MaterialDO> materialDOS = JsonKit.parseAsList(JsonKit.stringify(object), MaterialDO.class);
//                ZenData zenData = ZenData.create(data).put("contractId", data.get("id"));
//                materialDOS.forEach(materialDO -> {
//                    zenData.put("materialId", materialDO.getId()).put("number",0);
//                    zenEngine.execute("/do/put/con_material", zenData);
//                });
//            }
            field.put("value", fieldMap.get(field.get("id")));
        }
        data.put("field",contractField);
        zenEngine.execute("patch/contract_field", data);
        return ZenResult.success();
    }
}
